package com.voxel.sense.infomsg.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;

import com.example.com.common.utils.L;
import com.example.com.common.view.dialog.DialogCallBack;
import com.example.com.common.view.dialog.DialogImpl;
import com.example.com.common.view.dialog.IDialog;
import com.example.com.common.view.dialog.NumbProgressDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.OkUpload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.lzy.okserver.upload.UploadListener;
import com.lzy.okserver.upload.UploadTask;
import com.voxel.sense.infomsg.interfaces.listener.UploadListenerImp;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cyy.example.com.facotry.constants.CommonConstants;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.share.SPEngine;

/**
 * Created by ChenYiYao on 2017/12/8.
 */

public class UploadManager {
    //    private static UploadUtils UTILS;
    private static int num = 0;
    public static final String SERVER = CommonConstants.API_URL_PREFIX + "company/issue/uploadFile";//上传地址
    public static final String SERVER_TASK = CommonConstants.API_URL_PREFIX + "task/center/issueAccessory";//上传地址
    public static final String SERVER1 = CommonConstants.API_URL_PREFIX + "user/uploadHeadImg";//上传地址
    NumbProgressDialog mProgressdialog;
    private Dialog mMessageDialog;
    private boolean mIsShowFlag; //是否显示dialog
    private boolean mIsDestroy;  //销毁标记
    boolean isUploadComplete = false; //是否完成上传
    private Context mContext;
    private UploadTask<String> mTask;
    private String mDialogDes;


    /**
     * 销毁调用
     */
    public void onDestory() {
        doCancleUpLoad();
        mContext = null;
        mIsDestroy = true;
        mTask = null;
        mMessageDialog = null;
        mMessageDialog = null;


    }

    public UploadManager() {
        OkGo.getInstance().init(Factory.app()).setRetryCount(0);
    }

    public void setShowProgress(boolean flag) {
        mIsShowFlag = flag;
    }

    public void initProgressDialog(Context context, String des) {
        mContext = context;
        mDialogDes = des;
        if (mProgressdialog == null) {
            mProgressdialog = (NumbProgressDialog) DialogImpl.getInstance().shownNumberProgressDialog(mContext, des, 1000);
            progressListener();
        }
    }

    public void ProgressDialogCancele(boolean b) {
        mProgressdialog.setCanceledOnTouchOutside(b);
    }


    public void getPostUpRequest(String tag, Map<String, String> mapParams, List<String> listPath, Serializable extra1, final UploadListenerImp listener) {
        if (listPath != null) {
            List<File> files = new ArrayList<>();
            for (int i = 0; i < listPath.size(); i++) {
                files.add(new File(listPath.get(i)));
            }

            String user_id = SPEngine.getSPEngine().getUserInfo().getUser_id();
            String token = SPEngine.getSPEngine().getUserInfo().getSetMobileToken();
            List<String> pa = new ArrayList<>();
            pa.add(mapParams.get("companyId"));
            //这里是演示可以传递任何数据
            PostRequest<String> postRequest = OkGo.<String>post(SERVER)//

                    .headers("_userId", user_id)
                    .headers("Authorization", token)
                    .headers("device", "mobile")
                    .params(mapParams)
                    .addFileParams("photo", files)
                    .addUrlParams("companyId", pa)
                    .isMultipart(true)
                    .converter(new StringConvert());
            createUploadTask(tag, "", listener, postRequest);
            startUploadTask(listener);
        }
    }

    private void startUploadTask(UploadListenerImp listener) {
        if (listener != null) {
            listener.setTask(mTask);
        }
//            开始下载
        mTask.restart();
    }


    /**
     * 任务附近上传
     *
     * @param tag       标记这个上传时间的标记
     * @param mapParams 参数
     * @param deletPath 删除文件的路径
     * @param listPath  上传文件的路径
     * @param listener
     */
    public void getPostUpTaskFileRequest(String tag,String mapParams, List<String> deletPath, List<String> listPath,String formContents, final UploadListenerImp listener) {
        if (listPath != null) {
            List<File> files = new ArrayList<>();
            for (int i = 0; i < listPath.size(); i++) {
                files.add(new File(listPath.get(i)));
            }

            String user_id = SPEngine.getSPEngine().getUserInfo().getUser_id();
            String token = SPEngine.getSPEngine().getUserInfo().getSetMobileToken();
            List<String> pa = new ArrayList<>();
            pa.add(mapParams);
            //这里是演示可以传递任何数据
            PostRequest<String> postRequest = OkGo.<String>post(SERVER_TASK)//
                    .headers("_userId", user_id)
                    .headers("Authorization", token)
                    .headers("device", "mobile")
                    .addUrlParams("delFilePathList", deletPath)
                    .addUrlParams("taskNumber", pa)
              .params("formContents", formContents)
//                    .params("taskNumber", mapParams)
                    .addFileParams("files", files)
                    .isMultipart(true)
                    .converter(new StringConvert());
            createUploadTask(tag, "", listener, postRequest);
            startUploadTask(listener);
        }
    }


    /**
     * @param tag         上传任务的标记
     * @param extra1      上传过程回调时，Progress额外携带的参数
     * @param listener    监听
     * @param postRequest 请求实体
     */
    private void createUploadTask(String tag, Serializable extra1, UploadListenerImp listener, PostRequest<String> postRequest) {
        mTask = OkUpload.getInstance().request(tag, postRequest)
                .extra1(null)
                .register(new UploadListener<String>("upListenerTag") {
                    @Override
                    public void onStart(Progress progress) {

                        if (listener != null)
                            listener.onStart(progress);

                        if (mIsShowFlag && mProgressdialog != null) {
                            if (!mProgressdialog.isShowing()) {
                                mProgressdialog.show();
                            }
                            showUpLoadProgress((int) (progress.fraction * 1000), mDialogDes);
                        }
                    }

                    @Override
                    public void onProgress(Progress progress) {
                        if (listener != null)
                            listener.onProgress(progress);

                        if (mIsShowFlag && mProgressdialog != null) {
                            int proNumb = (int) (progress.fraction * 1000);
                            proNumb = (proNumb == 100) ? proNumb - 1 : proNumb;
                            showUpLoadProgress(proNumb, mDialogDes);
                        }
                    }

                    @Override
                    public void onError(Progress progress) {
                        if (listener != null)
                            listener.onError(progress);
                        UpComplateFresh();
                    }

                    @Override
                    public void onFinish(String entity, Progress progress) {
                        if (listener != null)
                            listener.onFinish(entity, progress);

                        UpComplateFresh();

                        UploadTask<?> task1 = OkUpload.getInstance().getTask(progress.tag);
                        if (task1 != null) {
                            task1.unRegister(progress.tag);
                        }
                    }

                    @Override
                    public void onRemove(Progress progress) {
                        if (listener != null) {
                            listener.onRemove(progress);
                        }
                        UpComplateFresh();
                    }
                }).save();
    }


    public DownloadTask getPostDownRequest(final String dir, final String fileName, String url, final DownloadListener listener) {
        GetRequest<File> request = OkGo.<File>get(url);
        DownloadTask save = OkDownload.request(url, request)
                .folder(dir)
                .fileName(fileName)
                .register(listener)
                .save();
        save.restart();
        return save;

    }

    public void showUpLoadProgress(int progress, String msg) {
        L.d("----------------------------------progress:" + progress);
        mProgressdialog.setCurrentProgress(progress);
        mProgressdialog.setTitle(msg);
    }


    private void progressListener() {
        mProgressdialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(final DialogInterface dialogInterface) {
                //当窗口消失时，需要判断上传是否完全结束
                //1.完成结束了，那么无需任何处理
                //2.没有结束，则需要弹出一个警告，告诉用户是否需要停止上传
                if (isUploadComplete) {
                    return;
                }
                if (mMessageDialog == null && !mIsDestroy && mContext != null) {
                    mMessageDialog = DialogImpl.getInstance().showChooseDialog(
                            mContext, "", "是否停止上传,取消任务执行单", "确定", "继续上传", new DialogCallBack() {
                                @Override
                                public void onClick(int what) {
                                    if (what == IDialog.CANCEL) {
                                        //停止上传
                                        doCancleUpLoad();
                                        //TODO:由于目前终止上传，服务器任务状态也变为已执行，不能再提交任务，暂时将提交按钮设置为不可用
//                                        btn_pass.setEnabled(false);
                                    } else {
                                        //继续上传
                                        if (mProgressdialog != null && !mIsDestroy) {
                                            mProgressdialog.show();
                                        }
                                        mMessageDialog.dismiss();
                                    }
                                }
                            });
                    mMessageDialog.setCancelable(false);
                    mMessageDialog.setCanceledOnTouchOutside(false);
                } else if (!mIsDestroy) {
                    mMessageDialog.show();
                }
            }
        });
    }


    public void doCancleUpLoad() {
        //停止上传
        OkUpload instance = OkUpload.getInstance();
        instance.pauseAll();
        instance.removeAll();
        OkGo.getInstance().cancelAll();
        if (mMessageDialog != null) {
            mMessageDialog.dismiss();
        }
        if (mTask != null) {
            mTask.unRegister("upListenerTag");
        }
        L.d("getPostUpRequest--------------------------doCancleUpLoad()");
        L.d("停止下载。。。。。");
    }


    /**
     * 上传动作完成后，刷新界面
     */
    private void UpComplateFresh() {
        isUploadComplete = true;
        if (mMessageDialog != null) {
            mMessageDialog.dismiss();
        }
        if (mProgressdialog != null) {
            mProgressdialog.dismiss();
        }
        doCancleUpLoad();
    }

    public void onUpLocadFailure() {
        isUploadComplete = true;
        //TODO:由于目前终止上传，服务器任务状态也变为已执行，不能再提交任务，暂时也更新ui为完成状态
//        UpComplateFresh();
    }
}
